package com.ai.fortune_matrix.service.impl;

/**
 * @Author: zjg
 * @Date: 2025/5/16 15:02
 * @Description:
 **/
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * * @author Christian Tzolov
 * 模拟的是一个航空公司 Funnair 的客户支持助手，具备：
 * 自然语言交互（ChatClient）
 * 记忆能力（ChatMemory）
 * 知识检索（RAG via VectorStore）
 * 函数调用（Function Calling）
 */
@Service
public class CustomerSupportAssistant {

    private final ChatClient.Builder modelBuilder;
    private final VectorStore vectorStore;
    private final ChatMemory chatMemory;
    private ChatClient chatClient;

    @Value("classpath:prompts/system-qa.st") // 确保路径正确
    private Resource systemResource;

    // 构造函数只接收依赖，不初始化 chatClient
    public CustomerSupportAssistant(ChatClient.Builder modelBuilder, VectorStore vectorStore, ChatMemory chatMemory) {
        this.modelBuilder = modelBuilder;
        this.vectorStore = vectorStore;
        this.chatMemory = chatMemory;
    }

    @PostConstruct  // 依赖注入完成后执行
    public void init() throws IOException {
        String promptTemplate = systemResource.getContentAsString(StandardCharsets.UTF_8);
        SearchRequest searchRequest = SearchRequest.builder().topK(4).similarityThresholdAll().build();

        this.chatClient = modelBuilder
                .defaultSystem(promptTemplate)
                .defaultAdvisors(
                        new PromptChatMemoryAdvisor(chatMemory),
                        new QuestionAnswerAdvisor(vectorStore, searchRequest),
                        new SimpleLoggerAdvisor()
                )
                .defaultFunctions("getLotteryDetails", "changeLottery", "cancelLottery")
                .build();
    }
    private String getPromptTemplate(Resource systemResource) {
        try {
            return systemResource.getContentAsString(StandardCharsets.UTF_8);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public Flux<String> chat(String chatId, String userMessageContent) {

        return this.chatClient.prompt()
                .system(s -> s.param("current_date", LocalDate.now().toString()))
                .user(userMessageContent)
                .advisors(
                        a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)) // 设置advisor参数，
                // 记忆使用chatId，
                // 拉取最近的100条记录
                .stream()
                .content();
    }

}
